<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getCoursesAdvanced">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="marketAdd">市场信息</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">图片信息</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleOnLine">课程上线</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleOffLine">课程下线</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="courses" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="名称" width="120" sortable>
			</el-table-column>
			<el-table-column prop="courseType.name" label="类型" width="120" sortable>
			</el-table-column>
			<el-table-column prop="tenantName" label="机构名称" width="120" sortable>
			</el-table-column>
			<el-table-column prop="userName" label="创建人" width="120" sortable>
			</el-table-column>
			<el-table-column prop="startTime" label="上线时间" width="120" sortable :formatter="formatOnSaleTime">
			</el-table-column>
			<el-table-column prop="endTime" label="下线时间" width="120" sortable :formatter="formatOffSaleTime">
			</el-table-column>
			<el-table-column prop="status" label="课程状态" min-width="120" sortable>
				<template scope="scope">
					<span style="color:green" v-if="scope.row.status==1">上线</span>
					<span style="color:red" v-else>下线</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
			</el-pagination>
		</el-col>



		<!--新增界面-->
		<el-dialog title="新增" :visible="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" ref="addForm">
				<el-form-item label="课程名称">
					<el-input v-model="addForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="适用人群">
					<el-input v-model="addForm.users" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="课程类型">
					<!--<el-input v-model="addForm.courseTypeId" auto-complete="off"></el-input>-->
					<el-cascader style="width: 100%" :props="props" :options="courseTypes" v-model="addForm.courseTypeId" clearable></el-cascader>
				</el-form-item>
				<el-form-item label="课程等级">
					<!--<el-input v-model="addForm.grade" auto-complete="off"></el-input>-->
					<el-radio @change="changeGrade" v-for="grade in courseGrades" v-model="addForm.grade" :label="grade.id">{{grade.name}}</el-radio>
				</el-form-item>
				<el-form-item label="课程介绍">
					<!--<el-input v-model="addForm.description" auto-complete="off"></el-input>-->
					<el-input v-model="addForm.description" type="textarea" auto-complete="off"></el-input>
				</el-form-item>

				<el-form-item label="课程简介">
					<!--<el-input v-model="addForm.intro" auto-complete="off"></el-input>-->
					<quill-editor v-model="addForm.intro">
					</quill-editor>

				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>


		<!--修改界面-->
		<el-dialog title="" :visible="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" ref="editForm">
				<el-form-item label="id">
					<el-input v-model="editForm.id" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="课程名称">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>

				<el-form-item label="适用人群">
					<el-input v-model="editForm.users" auto-complete="off"></el-input>
				</el-form-item>
				<!--<el-form-item label="课程类型">
					<el-input v-model="addForm.courseTypeId" auto-complete="off"></el-input>
					&lt;!&ndash;<el-cascader style="width: 100%" :props="props" :options="courseTypes" v-model="editForm.courseTypeId" clearable></el-cascader>&ndash;&gt;
				</el-form-item>-->
				<el-form-item label="课程等级">
					<!--<el-input v-model="addForm.grade" auto-complete="off"></el-input>-->
					<el-radio @change="changeGrade" v-for="grade in courseGrades" v-model="editForm.grade" :label="grade.id">{{grade.name}}</el-radio>
				</el-form-item>
				<el-form-item label="课程介绍">
					<!--<el-input v-model="addForm.description" auto-complete="off"></el-input>-->
					<el-input v-model="editForm.description" type="textarea" auto-complete="off"></el-input>
				</el-form-item>

				<el-form-item label="课程简介">
					<!--<el-input v-model="addForm.intro" auto-complete="off"></el-input>-->
					<quill-editor v-model="editForm.intro">
					</quill-editor>

				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="addLoading">提交a</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
   import { getCourseListPage, removeCourse, batchRemoveCourse, editCourse, addCourse } from '../../api/api';


    import { quillEditor } from 'vue-quill-editor'
    import 'quill/dist/quill.snow.css' // 富文本编辑器外部引用样式  三种样式三选一引入即可
    import 'quill/dist/quill.core.css'
    import 'quill/dist/quill.bubble.css'

    export default {
        components: {
            quillEditor
        },
        data() {
            return {
                courseGrades:[],
                courseTypes:[],//课程类型
                props:{
                    label:"name",
                    children:"children",
                    value:"id"
                },
                filters: {
                    keyword: ''
                },
                courses: [],
                total: 0,
                pageSize:10,
                page: 1,
                listLoading: false,
                sels: [],//列表选中列

                marketFormVisible: false,

                editFormVisible: false,//编辑界面是否显示
                editLoading: false,
                //编辑界面数据
                editForm: {
                    id: 0,
                    name: '',
                    sex: -1,
                    age: 0,
                    birth: '',
                    addr: ''
                },

                addFormVisible: false,//新增界面是否显示
                addLoading: false,
                //新增界面数据
                addForm: {
                    name: '',
                    users:'',
                    courseTypeId:null,
                    grade:null,
                    gradeName:'',
                    description:'',
                    intro:''
                }

            }
        },
        methods: {
            //上线
            handleOnLine:function () {
                //获取选中行的id
                //es6的map方法  遍历每一个元素，通过function将元素进行运算，结果放入一个新的数组中返回
                let ids = this.sels.map(course=>{
                    return course.id;
                })

                if(this.sels.length<=0){
                    this.$message({
                        type: 'warning',
                        message: '至少选中一行数据!'
                    });
                    return;
                }


                this.$confirm('确定上线这些课程?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.axios.post("/course/course/onLine",ids)
                        .then(res=>{
                            let {success,message} = res.data;
                            if(success){
                                this.$message({
                                    message:"上线成功!",
                                    type:"success"
                                })
                                this.page = 1;
                                this.getCourses();
                            }else{
                                this.$message({
                                    message:message,
                                    type:"success"
                                })
                            }

                        })
                });

            },
			//下线
            handleOffLine:function () {
                let ids = this.sels.map(course => {
                    return course.id;
                })
                if (this.sels.length <= 0) {
                    this.$message({
                        type: 'warning',
                        message: '至少选中一行数据!'
                    });
                    return;
                }
                this.$confirm('确定下线这些课程?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.axios.post("/course/course/offLine", ids)
                        .then(res => {
                            let {success, message} = res.data;
                            if (success) {
                                this.$message({
                                    message: "下线成功!",
                                    type: "success"
                                })
                                this.page = 1;
                                this.getCourses();
                            } else {
                                this.$message({
                                    message: message,
                                    type: "success"
                                })
                            }
                        })
                });
            },
            //等级选项改变的事件
            changeGrade(label){
                for(let i=0;i<this.courseGrades.length;i++){
                    if(label == this.courseGrades[i].id){
                        this.addForm.gradeName = this.courseGrades[i].name;
                    }
                }
            },
            //课程等级数据加载
            getCourseGrades(){
                this.axios.get("/system/systemdictionaryitem/listBySn?sn=dj")
                    .then(res=>{
                        this.courseGrades = res.data;
                    })
            },
            // 递归判断列表，把最后的children设为undefined
            getTreeData(data){
                for(var i=0;i<data.length;i++){
                    if(data[i].children.length<1){
                        // children若为空数组，则将children设为undefined
                        data[i].children=undefined;
                    }else {
                        // children若不为空数组，则继续 递归调用 本方法
                        this.getTreeData(data[i].children);
                    }
                }
                return data;
            },
            //课程类型数据加载
            getCourseTypes(){
                this.axios.get("/course/courseType/tree")
                    .then(res=>{
                        this.courseTypes = this.getTreeData(res.data);
                    })
            },
            //高级查询
            getCoursesAdvanced(){
                this.page = 1;
                this.getCourses();
            },
            //格式化上线时间
            formatOnSaleTime(row, column){
                let time = this.$moment(new Date(row.startTime)).format('YYYY-MM-DD')
                return time
            },
            //格式化下线时间
            formatOffSaleTime(row, column){
                let time = this.$moment(new Date(row.endTime)).format('YYYY-MM-DD')
                return time
            },
           /* formatTime(time){
                if(!time){
                    return "";
                }
                let date = new Date(time);
                return date.getFullYear()+"-"+this.formatNum((date.getMonth()+1))+"-"+this.formatNum(date.getDay());
            },
            formatNum(num){
                if(num<10){
                    return "0"+num;
                }
                return num;
            },*/
            handleCurrentChange(val) {
                this.page = val;
                this.getCourses();
            },
            //获取课程列表
            getCourses() {
                let para = {
                    page: this.page,
                    rows: this.pageSize,
                    keyword: this.filters.keyword
                };
                this.listLoading = true;
                this.axios.post("/course/course/pagelist",para)
                    .then(res=>{
                        this.listLoading = false;
                        this.total = res.data.total;
                        this.courses = res.data.rows;
                    })
            },
            /*************************************************/
            marketAdd: function () {
                alert()
                this.axios.post("/course/course/pagelist").then(res=>{
                    alert(1)
				})
                alert()

			},
            /*************************************************/
            //删除
            handleDel: function (index, row) {
                //删除1条数据
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //把id传到后台删除
                    this.$http.delete("/course/course/"+row.id)
                        .then(res=>{
                            this.listLoading = false;
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            this.getCourses();
                        });
                });

            },

            //显示编辑界面
            handleEdit: function (index, row) {
                this.editFormVisible = true;
                this.editForm = Object.assign({}, row);
            },
            //显示新增界面
            handleAdd: function () {
                this.addFormVisible = true;
                this.addForm = {
                    name: '',
                    sex: -1,
                    age: 0,
                    birth: '',
                    addr: ''
                };
            },
/*************************************************/
           /* marketAdd: function () {
                this.addFormVisible = true;
                this.addForm = {
                    name: '',
                    sex: -1,
                    age: 0,
                    birth: '',
                    addr: ''
                };
            },*/
            /*************************************************/
            //编辑
            editSubmit: function () {
                this.$refs.editForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.addLoading = true;
                            //NProgress.start();
                            let para = Object.assign({}, this.editForm);
                            //重新设置课程类型
                            para.courseTypeId = para.courseTypeId?para.courseTypeId[para.courseTypeId.length-1]:null;
                            this.axios.post("/course/course/add",para)
                                .then(res=>{

                                    this.addLoading = false;

                                    let {success,message} = res.data;
                                    if(success){
                                        //成功
                                        this.$message({
                                            message:message,
                                            type:"success"
                                        })
                                        //关闭模态框
                                        this.editFormVisible = false;
                                        //重新加载数据
                                        this.page = 1;
                                        this.getCourses();
                                    }else{
                                        this.$message({
                                            message:message,
                                            type:"error"
                                        })
                                    }
                                })
                        });
                    }
                });
            },
            //新增
            addSubmit: function () {
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.addLoading = true;
                            //NProgress.start();
                            let para = Object.assign({}, this.addForm);
                            //重新设置课程类型
                            para.courseTypeId = para.courseTypeId?para.courseTypeId[para.courseTypeId.length-1]:null;
                            this.axios.post("/course/course/add",para)
                                .then(res=>{

                                    this.addLoading = false;

                                    let {success,message} = res.data;
                                    if(success){
                                        //成功
                                        this.$message({
                                            message:message,
                                            type:"success"
                                        })
                                        //关闭模态框
                                        this.addFormVisible = false;
                                        //重新加载数据
                                        this.page = 1;
                                        this.getCourses();
                                    }else{
                                        this.$message({
                                            message:message,
                                            type:"error"
                                        })
                                    }
                                })
                        });
                    }
                });
            },
            selsChange: function (sels) {
                this.sels = sels;
            },
            //批量删除
            batchRemove: function () {
                var ids = this.sels.map(item => item.id).toString();
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    let para = { ids: ids };
                    batchRemoveCourse(para).then((res) => {
                        this.listLoading = false;
                        //NProgress.done();
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.getCourses();
                    });
                }).catch(() => {

                });
            }
        },
        mounted() {
            this.getCourses();
            this.getCourseTypes();
            this.getCourseGrades();
            console.log("addForm",this.addForm)
        }
    }

</script>

<style scoped>

</style>